<docs lang="markdown">
Demo plugin to demonstrate how to plot charts in ImJoy. For this, some data is generated
in a Pythons plugin andd displayed in a separate window.

Here, we create an image (`.png`) in the Python plugin. This image is then send
to a window plugin and displayed there. Such an image is not restricted to simple charts,
and can thus also contain more complex data which can not be send by the plugin communicatino protocols.


</docs>

<config lang="json">
{
  "name": "Process Inline Hologram",
  "type": "window",
  "version": "0.0.2",
  "api_version": "0.1.2",
  "description": "Sending Image to the IMJOY plugin to backpropagate it into the sample plane.",
  "tags": [],
  "ui": [
          "Distance to the sensor plane: {id:'z_dist', type: 'number', min: 0, placeholder:1e-3}"
        ],
  "inputs": null,
  "outputs": null,
  "flags": [],
  "icon": "swap_horiz",
  "env": null,
  "requirements": [
    "https://unpkg.com/spectre.css/dist/spectre.min.css",
    "https://unpkg.com/spectre.css/dist/spectre-exp.min.css",
    "https://unpkg.com/spectre.css/dist/spectre-icons.min.css"
  ],
  "dependencies": ["bionanoimaging/UC2-ImJoy-GIT:UC2 Holorecon"]
}
</config>

<script lang="javascript">
class ImJoyPlugin {
  async setup() {

    // bind predict() to the button
    const processBtn = document.getElementById('process-btn');
    const fileInput = document.getElementById("file-input");
    const canvas = document.getElementById("input-canvas");

    processBtn.onclick = async ()=>{
      try{
        const base64_url = canvas.toDataURL()
        const pluginHolorecon = await api.getPlugin('UC2 Holorecon')
        await pluginHolorecon.process_hologram(base64_url)
        await api.alert('Process done!')
      }
      catch(e){
        console.error(e)
        await api.alert('Failed to process, error: ' + e)
      }
    }

    // Display image when a file is selected.
    const drawImage = (url, callback)=>{
        var img = new Image()
        img.crossOrigin = "anonymous"
        img.onload = function(){
            const ctx = canvas.getContext("2d");
            canvas.width = Math.min(this.width, 512);
            canvas.height= Math.min(this.height, parseInt(512*this.height/this.width), 1024);
            // draw the img into canvas
            ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
            if(callback) callback(canvas.toDataURL());
        }
        img.src = url;
    }

    //load a preset image

    drawImage('https://raw.githubusercontent.com/bionanoimaging/UC2-GIT/master/WORKSHOP/INLINE-HOLOGRAMM/PYTHON/hologram_mouse.jpg')

    const readImageFile = ()=>{
        return new Promise((resolve, reject)=>{
            const U = window.URL || window.webkitURL;
            // this works for safari
            if(U.createObjectURL){
                drawImage(U.createObjectURL(fileInput.files[0]), resolve)
            }
            // fallback
            else{
                var fr = new FileReader();
                // when image is loaded, set the src of the image where you want to display it
                fr.onload = function(e) {
                    drawImage(e.target.result, resolve)
                };
                fr.onerror = reject
                // fill fr with image data
                fr.readAsDataURL(fileInput.files[0]);
            }
        })
    }

    // If user selected a new file or take a new photo, load it and do prediction.
    fileInput.addEventListener("change", async ()=>{
      try{
        const base64_url = await readImageFile()
        const pluginHolorecon = await api.getPlugin('UC2 Holorecon')
        await pluginHolorecon.process_hologram(base64_url)
        await api.alert('Process done!')
      }
      catch(e){
        console.error(e)
        await api.alert('Failed to process, error: ' + e)
      }

    }, true);


    const statusElement = document.getElementById("status");
    //document.getElementById("hero_title").innerHTML = 'Model loaded'
    statusElement.innerHTML = '1. Open image (.png/.jpg) or use pre-loaded image. <br> 2. Click `Compute` to refocus the image!';

    // Display the predict button and file selection
    processBtn.style.display = "inline";
    fileInput.style.display = "inline";
  }
  run(){

  }
}
api.export(new ImJoyPlugin())
</script>


<window lang="html">
  <div>
    <!–– Header bar ––>
    <div class="hero hero-sm bg-secondary">
        <div class="mx-2">
            <!-- <h3 id="hero_title"></h3> -->
            <p id="status"></p>
        </div>
    </div>

   <!–– Buttons ––>
   <div class="p-1">
        <input  style="display: none;" id="file-input" accept="image/*" capture="camera" type="file"/>
        <br>
        <button class="btn btn-primary" style="display: none;" id="process-btn">Compute</button>
    </div>

    <!–– canvas ––>
    <div class="p-1">
        <canvas id="input-canvas" style="width: 100%; object-fit: cover;"></canvas>
    </div>
  </div>
</window>

<style lang="css">
.p-1 {
    text-align: center;
}
.p-1 input{
    width:90%;
    margin:10px;
}
.p-1 button{
    width:90%;
    margin:10px;
}
</style>
